/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.donkingliang.imageselector;

import com.donkingliang.imageselector.util.Constant;
import com.donkingliang.imageselector.util.HeLog;
import com.yalantis.ucrop.util.LogUtils;
import com.yalantis.ucrop.view.CropResult;
import com.yalantis.ucrop.view.GestureCropImageView;
import com.yalantis.ucrop.view.UCropView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.data.rdb.ValuesBucket;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 图片裁剪
 *
 * @author Hexy
 * @since 2021-04-23
 */
public class ImageAbility extends Ability implements CropResult {
    private UCropView mUcropView;
    private Text tvLift;
    private Text tvAmplification;
    private Text tvLessen;

    /**
     * onStart
     *
     * @param intent intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_ucropview);

        // 本地URI
        tvLift = (Text) findComponentById(ResourceTable.Id_tv_lift);
        tvAmplification = (Text) findComponentById(ResourceTable.Id_tv_amplification);
        tvLessen = (Text) findComponentById(ResourceTable.Id_tv_lessen);
        PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
        options.size = new Size(Constant.IMAGESIZE, Constant.IMAGESIZE);
        PixelMap pixelmap = PixelMap.create(options);
        String filename = "test.jpg";
        Uri uriPath = saveImage(filename, pixelmap);
        String urlpath = intent.getStringParam("img");

        // 网图URI
        // 待裁剪图片的URI
        Uri uriI = Uri.parse(urlpath);
        mUcropView = (UCropView) findComponentById(ResourceTable.Id_ucv_pic);
        mUcropView.getCropImageView().setImageUri(uriI, uriPath);
        mUcropView.getOverlayView().setShowCropFrame(true);
        mUcropView.getOverlayView().setShowCropGrid(true);
        mUcropView.getOverlayView().setDimmedColor(Color.TRANSPARENT.getValue());
        Text tvRight = (Text) findComponentById(ResourceTable.Id_tv_right);
        Text tvCrop = (Text) findComponentById(ResourceTable.Id_tv_crop);

        // 裁剪Button
        tvCrop.setClickedListener(component -> cropAndSaveImage());

        // 旋转+90Button
        tvRight.setClickedListener(component -> {
            float degrees = Constant.NANZOREF;

            // 计算旋转中心
            float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX();
            float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY();

            // 旋转
            mUcropView.getCropImageView().postRotate(degrees, centerX, centerY);

            // 适配
            mUcropView.getCropImageView().setImageToWrapCropBounds(false);
        });

        setListener();
    }

    /**
     * 事件监听
     */
    public void setListener() {
        // 旋转-90Button
        tvLift.setClickedListener(component -> {
            float degrees = Constant.NANZOREFU;

            // 计算旋转中心
            float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX();
            float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY();

            // 旋转
            mUcropView.getCropImageView().postRotate(degrees, centerX, centerY);

            // 适配
            mUcropView.getCropImageView().setImageToWrapCropBounds(false);
        });

        // 缩放x2 Button
        tvLessen.setClickedListener(component -> {
            float factor = Constant.SECONDF;

            // 计算旋转中心
            float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX();
            float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY();

            // 旋转
            mUcropView.getCropImageView().postScale(factor, centerX, centerY);

            // 适配
            mUcropView.getCropImageView().setImageToWrapCropBounds(true);
        });

        // 缩放/2 Button
        tvAmplification.setClickedListener(component -> {
            float factor = Constant.ZOREFIVE;

            // 计算旋转中心
            float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX();
            float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY();

            // 旋转
            mUcropView.getCropImageView().postScale(factor, centerX, centerY);

            // 适配
            mUcropView.getCropImageView().setImageToWrapCropBounds(false);
        });
    }

    /**
     * 裁剪图片
     */
    protected void cropAndSaveImage() {
        GestureCropImageView crop = mUcropView.getCropImageView();
        crop.onCropResult(this);
        crop.cropAndSaveImage("image/jpg",
                Constant.NANZORE, null, getContext());
        LogUtils.LogInfo("qqqqqqq:", "cropAndSaveImage");
    }

    private Uri saveImage(String fileName, PixelMap pixelMap) {
        Uri uri = null;
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG");

            // 应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(this);
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));

            // 这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);
            packingOptions.format = "image/jpeg";
            packingOptions.quality = Constant.NANZORE;
            boolean isResult = imagePacker.initializePacking(outputStream, packingOptions);
            if (isResult) {
                isResult = imagePacker.addImage(pixelMap);
                if (isResult) {
                    imagePacker.finalizePacking();
                }
            }
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                HeLog.d("TAG", "IOException");
            }
            valuesBucket.clear();

            // 解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
        } catch (FileNotFoundException | DataAbilityRemoteException e) {
            HeLog.d("TAG", "DataAbilityRemoteException");
        }
        return uri;
    }

    /**
     * onActive
     */
    @Override
    public void onActive() {
        super.onActive();
    }

    /**
     * onForeground
     *
     * @param intent intent
     */
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * 回調
     *
     * @param path path
     */
    @Override
    public void onCropResult(String path) {
        Intent fileIntent = new Intent();
        fileIntent.setParam("extra_result_items", path);
        setResult(Constant.REQ_PERMISSION_CODE, fileIntent);
        terminateAbility();
    }
}